package com.googlecode.javaexamples.multithreading.ringbuffer;

public class Main {

    public static void main(String[] args) {
        Object lockObject = new Object();
        int messagesCount = 0;
        RingBuffer<String> additionalBuffer = new RingBuffer<String>();
        RingBuffer<String> mainBuffer = new RingBuffer<String>();

        final int writerPoolSize = 5;
        WriterThread[] writerPool = new WriterThread[writerPoolSize];

        final int readerPoolSize = 2;
        ReaderThread[] readerPool = new ReaderThread[readerPoolSize];

        for (int i = 0; i < writerPoolSize; ++i) {
            writerPool[i] = new WriterThread(additionalBuffer, lockObject);
            writerPool[i].start();
        }

        for (int i = 0; i < readerPoolSize; ++i) {
            readerPool[i] = new ReaderThread(additionalBuffer, mainBuffer,
                    lockObject);
            readerPool[i].start();
        }

        while (messagesCount < 100) {
            synchronized (lockObject) {
                if (mainBuffer.elementCount() > 0) {
                    System.out.println("Main pop: " + mainBuffer.pop());
                    ++messagesCount;
                    lockObject.notifyAll();
                } else {
                    try {
                        lockObject.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
